import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'
import './assets/styles/responsive.scss'
import './assets/styles/tailwind.css'
import axios from 'axios'

import App from './App.vue'
import router from './router'
import { wsService } from './services/websocket.service'

const app = createApp(App)
const pinia = createPinia()

// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 设置axios默认配置
axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL || '/api'

// 设置axios请求拦截器，添加token
const token = localStorage.getItem('token')
if (token) {
  axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
}

// 设置axios响应拦截器，处理401错误
axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      // 清除token和用户信息
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      // 如果不是登录页，跳转到登录页
      if (window.location.pathname !== '/login') {
        window.location.href = '/login'
      }
    }
    return Promise.reject(error)
  }
)

app.use(pinia)
app.use(router)
app.use(ElementPlus)

// 初始化 WebSocket 连接
wsService.connect()

app.mount('#app') 